import { useCallback, useEffect, useMemo, useState } from "react";
import SearchTop from "../../../components/userlist/SearchTop";
import ButtonGroup from "../../../components/userlist/ButtonGroup";
import TableList from "../../../components/userlist/TableList";
import PageNavigition from "../../../components/userlist/PageNavigition";
import { getUserList } from "../../../business/UserListRequest";
import { DataType, IUserListItem } from "../../../interface/IUserList";
import AddAndEdit from "../../../components/userlist/AddAndEdit";

export default function UserView() {
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(10);
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0);
  const [selectList, setSelecteList] = useState<number[]>([]);
  const [loading, setLoading] = useState(false);
  const [isShow, setIsShow] = useState(false);
  const [editData,setEditData]=useState<DataType|null>(null);
  useEffect(() => {
    setLoading(true);
    getUserList({ page, size }).then((res) => {
      setTotal(res.total);
      setDataSource(
        res.users.map((item: IUserListItem) => ({ ...item, key: item.id }))
      );
      setLoading(false);
    });
  }, [page, size]);

  const disabled = useMemo(() => {
    return selectList.length === 0;
  }, [selectList]);

  useEffect(()=>{
    if(editData) setIsShow(true)
      else setIsShow(false)
  },[editData])
  
  useEffect(()=>{
    if(!isShow) setEditData(null)
  },[isShow])

  const searchHandler = (ename: string, uname: string) => {
    console.log(ename, uname);
  };
  return (
    <div>
      <SearchTop searchHandler={searchHandler} />
      <ButtonGroup disabled={disabled} setIsShow={setIsShow} />
      <TableList
        dataSource={dataSource}
        setSelecteList={setSelecteList}
        selectList={selectList}
        loading={loading}
        setEditData={setEditData}
      />
      <PageNavigition
        setPage={setPage}
        setSize={setSize}
        page={page}
        size={size}
        total={total}
      />
      <AddAndEdit isShow={isShow} setIsShow={setIsShow} editData={editData}/>
    </div>
  );
}
